import React, { PureComponent } from 'react'
import { history } from '@umijs/max'
import {
  Button, Form, message, Popover, Radio, Tabs, Tooltip,
} from 'antd'
import FieldMapping from 'react-field-mapping'
import { BreadcrumbBar, CreateDiffEditor, ProTable } from '@/components'

import { getDetailInfo, getTableFields, previewDataForMq } from './api'
import { getHashParameterByName } from '@/utils/helper'
import styles from './index.less'

const sourceCols = [
  { title: '源字段', key: 'fieldName', width: '2rem' },
  { title: '类型', key: 'fieldType' },
  {
    title: '非空',
    key: 'nullable',
    width: '0.5rem',
    render: (nullable) => (nullable ? '-' : '是'),
  },
  { title: '描述', key: 'comment' },
]
const influxDBCols = [
  { title: '源字段', key: 'fieldName', width: '2rem' },
  { title: '类型', key: 'fieldType' },
  {
    title: '是否是Tag',
    key: 'targetTag',
    render: (targetTag) => {
      console.log(targetTag)
      return targetTag ? '是' : '否'
    },
  },
  { title: '描述', key: 'comment' },
]

const { TabPane } = Tabs
const { Item } = Form

export default class SersyncDetail extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      id: getHashParameterByName('id'),
      menus: [{ name: '实时同步' }, { name: '查看' }],
      data: null,
      sourceFields: [],
      targetFields: [],
      relation: [],
      functionStr: `function parseJson(inputParam) {
  // inputParam为返回报文的JSON字符串
  // var dataObj = JSON.parse(inputParam)
  // var result=[['参数1','参数2','...']]  // 定义参数名
  // var 参数1 = dataObj.errno //输入根节点数据
  // for(i=0; i < dataObj.xx.length; i++) {  // 此处输入处理逻辑,以循环遍历为例
  //    var arr = [] 
  //    var 参数2 = dataObj.xx[0].yy  // 输入叶子节点数据
  //    arr.push(参数1)
  //    arr.push(参数2)
  //    result.push(arr) 
  // }
  // return result 
}`,
      velocity: `$iot.setStorageGroupDirect($IOT_DATA_MODEL,"root.ninggang")
$iot.setDeviceIdFromJson($IOT_DATA_MODEL,"&.sn")
$iot.setTimestampFromJson($IOT_DATA_MODEL,"&.time")
#set($result=$iot.setMeasurementFromJson($IOT_DATA_MODEL,"&.data.YS_YS.*","id","value"))`,
    }
    this.editorJsEditId = `${Math.random()}`
  }

  componentDidMount() {
    this.getDetailInfo()
  }

  getDetailInfo = () => {
    const { id } = this.state
    getDetailInfo({ id }).then(async (res) => {
      if (res.status === 200) {
        message.success(res.msg)
        if (!res.data) return
        let targetFields = []; let sourceFields = []; let relation = []

        if (res.data.sourceDsType === 'Mongodb' || res.data.sourceDsType === 'HBase') {
          sourceFields = []
          res.data && res.data.fieldMappings && res.data.fieldMappings.map((item) => {
            sourceFields.push({
              fieldName: item.sourceField,
              fieldType: item.sourceFieldType,
              key: item.sourceField,
            })
          })
        } else if (res.data.sourceDsType === 'Kafka' || res.data.sourceDsType === 'MQTT') {
          res.data && res.data.tableData && res.data.tableData.map((item) => {
            sourceFields.push({
              fieldName: item,
              fieldType: '',
              key: item,
            })
          })
        } else {
          sourceFields = await this.getTableFields(res.data.sourceDsId, res.data.sourceTableOrTopic)
        }

        if (res.data.targetDsType === 'Kafka' || res.data.targetDsType === 'MQTT' || res.data.targetDsType === 'Mongodb' || res.data.targetDsType === 'HBase') {
          targetFields = []
          res.data && res.data.fieldMappings && res.data.fieldMappings.map((item) => {
            targetFields.push({
              fieldName: item.targetField,
              fieldType: item.targetFieldType,
              key: item.targetField,
            })
          })
        } else if (res.data.targetDsType === 'InfluxDB') {
          targetFields = []
          res.data && res.data.fieldMappings && res.data.fieldMappings.map((item) => {
            targetFields.push({
              fieldName: item.targetField,
              fieldType: item.targetFieldType,
              targetTag: !!item.isTargetTag,
              key: item.targetField,
            })
          })
        } else if (res.data.targetDsType !== 'Kafka' && res.data.targetDsType !== 'MQTT') {
          targetFields = await this.getTableFields(res.data.targetDsId, res.data.targetTableOrTopic)
        }

        relation = await this.setRelation(res.data)
        this.setState({
          data: res.data,
          sourceFields,
          targetFields,
        }, () => {
          this.setState({
            relation,
          })
        })
      } else {
        message.error(res.msg)
      }
    })
  }

  getTableFields = (dsId, tables) => new Promise((resolve, reject) => {
    getTableFields({ dsId, tableName: tables }).then((res) => {
      if (res.status === 200) {
        const data = res.data || []
        data.map((item) => {
          item.key = item.fieldName
          item.isPk = item.pk ? 1 : 0
        })
        resolve(data)
      } else {
        reject(res)
      }
    })
  })

  setRelation = (data) => new Promise((resolve, reject) => {
    const relation = []
    data && data.fieldMappings && data.fieldMappings.map((item) => {
      relation.push({
        source: {
          fieldName: item.sourceField,
          fieldType: item.sourceFieldType,
          isPk: item.isSourceFieldPk,
          comment: item.comment,
          key: item.sourceField,
        },
        target: {
          fieldName: item.targetField,
          fieldType: item.targetFieldType,
          isPk: item.isTargetFieldPk,
          comment: item.comment,
          key: item.targetField,
        },
      })
    })
    resolve(relation)
  })

  handlePreview = () => {
    const { data } = this.state
    this.setState({
      tableViewLoading: true,
    })
    previewDataForMq({
      anaysisType: Number(data.useJsFlag),
      mqType: data.sourceDsType,
      jsonContent: data.jsContent,
      fieldInfoList: data.fieldExpressRequests,
      topic: data.sourceTableOrTopic,
      dsId: data.sourceDsId,
    }).then((res) => {
      const datas = res.data
      const tablePreview = []
      const tablePreviewColumn = []
      if (res.status === 200) {
        if (!datas) return
        datas[0]
          && datas[0].map((item) => {
            tablePreviewColumn.push({
              title: item,
              dataIndex: item,
              key: item,
              width: 100,
              render: (txt) => (<div className={styles.td_ellipse} title={txt}>{txt}</div>),
            })
            return null
          })

        datas.slice(1).map((item) => {
          const obj = {}
          datas[0].map((val, key) => {
            obj[val] = `${item[key]}` // + ''  为了容错，后端返回的值为 对象类型
            return null
          })
          tablePreview.push(obj)
          return null
        })
        this.setState({
          tablePreview,
          tablePreviewColumn,
        })
        message.success(res.msg)
      } else {
        message.error(res.msg)
      }
      this.setState({
        tableViewLoading: false,
      })
    })
  }

  render() {
    const {
      menus, data, sourceFields, targetFields, relation, tableViewLoading, tablePreviewColumn, tablePreview,
    } = this.state
    // console.log((data && data.sourceDsType !== 'Mongodb' && data.targetDsType === 'Kafka') || (data && data.targetDsType === 'MQTT'), '详情')
    return (
      <div className={`${styles.page_content_with_breadcrumb} ${styles.page_content_tabs_height}`}>
        <BreadcrumbBar menu={menus} />
        <div className={styles.back_bar}>
          <i className="iconfont icon-zuo" />
          <span onClick={() => { history.push('/dataIntegrate/sersync') }}>查看</span>
        </div>
        <div className={styles.page_content}>
          <div className={styles.page_content_right}>
            <Form
              className={styles.form}
              colon={false}
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 20 }}
            >
              <Form.Item>
                <div className={styles.column}>基础设置</div>
              </Form.Item>
              <Form.Item
                label="任务名称"
              >
                <div className={`${styles.form_item} ${styles.text_overflow_single}`} title={data && data.taskName}>{data && data.taskName}</div>
              </Form.Item>
              <Form.Item>
                <div className={styles.column}>数据来源</div>
              </Form.Item>
              <Form.Item
                label="数据来源"
              >
                <div className={`${styles.form_item} ${styles.text_overflow_single}`} title={data && data.sourceDsName}>{data && data.sourceDsName}</div>
              </Form.Item>
              <Form.Item
                label={data && data.sourceDsType === 'Kafka' ? 'Topic' : '来源表'}
              >
                <div className={`${styles.form_item} ${styles.text_overflow_single}`} title={data && data.sourceTableOrTopic}>{data && data.sourceTableOrTopic}</div>
              </Form.Item>
              {(data && data.sourceDsType === 'MySQL') || (data && data.sourceDsType === 'Oracle') ? (
                <Form.Item
                  label={
                    <span>采集起点
                      <Tooltip
                        placement="topRight"
                        title={
                          <div><p>Initial：从源头第一行数据开始采集</p>
                            <p>latest-offset：从当前提交任务开始采集数据</p>
                          </div>
                        }
                      ><i className="iconfont icon-yiwentishi" />
                      </Tooltip>
                    </span>
                  }
                >
                  <Radio.Group value={data && data.start} disabled>
                    <Radio value={0}>initial</Radio>
                    <Radio value={1}>latest-offset</Radio>
                  </Radio.Group>
                </Form.Item>
              ) : null}
              {(data && data.sourceDsType === 'Kafka') || (data && data.sourceDsType === 'MQTT') ? (
                <div>
                  <Tabs
                    destroyInactiveTabPane
                    activeKey={data ? String(data.useJsFlag) : '0'}
                  >
                    <TabPane tab="默认" key="0" className={styles.tab_pane_height}>
                      {data && data.fieldExpressRequests && data.fieldExpressRequests.map((item, index) => (
                        <Item
                          labelCol={index === 0 ? { span: 5 } : { span: 0 }}
                          wrapperCol={index === 0 ? { span: 19 } : { span: 19, offset: 5 }}
                          label={index === 0 ? (
                            <span>
                              结果变量名
                              <Popover
                                content={
                                  <span>
                                    点击
                                    <span
                                      style={{ color: '#0084FF', cursor: 'pointer' }}
                                      onClick={() => {
                                        window.open(`${window.suanpan}Json.html`)
                                      }}
                                    >
                                      {' '}这里{' '}
                                    </span>
                                    查看Json解析说明
                                  </span>
                                }
                              >
                                <i className="iconfont icon-yiwentishi" />
                              </Popover>
                            </span>
                          ) : ''}
                          key={index}
                        >
                          <div className={styles.parameter_item}>
                            <Item
                              noStyle
                              style={{ display: 'inline-block', width: 'calc(50% - 8px)' }}
                            >
                              <span>{item.fieldName}</span>
                            </Item>
                            <span className={styles.equal_sign}> = </span>
                            <Item
                              noStyle
                              style={{ display: 'inline-block', width: 'calc(50% - 8px)' }}
                            >
                              <span>{item.fieldExpress}</span>
                            </Item>
                          </div>
                        </Item>
                      ))}
                    </TabPane>
                    <TabPane tab="自定义" key="1" className={styles.tab_pane_height}>
                      <div className={`${styles.api_bottom_out_example} ${styles.api_bottom_out_example_custom}`}>
                        <CreateDiffEditor
                          readOnly
                          language="javascript"
                          theme="vs"
                          editorId={this.editorJsEditId}
                          ref={this.customEditorRef}
                          restData={data && data.jsContent || this.state.functionStr}
                        />
                      </div>
                    </TabPane>
                    <TabPane
                      tab={
                        <span>velocity
                          <Tooltip
                            placement="top"
                            title={
                              <div>
                                <p>IoTDB专用</p>
                                <p>{
                                  `说明：
                                  解析脚本遵循jsonpath和velocity语法，需要将jsonpath中代表根元素的$替换为&，见示例
                                  $iot、$IOT_DATA_MODEL为解析脚本保留字
                                  .setXXX(...)为方法调用
                                  支持的velocity解析方法如下：
                                  1.设置存储组名称 setStorageGroupDirect($IOT_DATA_MODEL,"name")
                                  2.设置存储组名称，jsonpath解析后得到 setStorageGroupFromJson($IOT_DATA_MODEL,"jsonpath")
                                  3.设置设备名称 setDeviceIdDirect($IOT_DATA_MODEL,"deviceName")
                                  4.设置设备名称，jsonpath解析后得到 setDeviceIdFromJson($IOT_DATA_MODEL,"jsonpath")
                                  5.设置时间戳，jsonpath解析后得到 setTimestampFromJson($IOT_DATA_MODEL,"jsonpath")
                                  6.指定日期格式，设置时间戳，jsonpath解析后得到 setTimestampFromJson($IOT_DATA_MODEL,"jsonpath","timeformat")
                                  7.设置测点值，jsonpath解析后得到 setMeasurementFromJson($IOT_DATA_MODEL,"jsonpath","idKey","valueKey")`
                                }
                                </p>
                              </div>
                            }
                          >
                            <i className="iconfont icon-yiwentishi" />
                          </Tooltip>
                        </span>
                      }
                      key="2"
                      className={styles.tab_pane_height}
                    >
                      <div className={`${styles.api_bottom_out_example} ${styles.api_bottom_out_example_custom}`}>
                        <CreateDiffEditor
                          language="velocity"
                          theme="vs"
                          editorId={this.editorJsEditId}
                          ref={this.customEditorRef}
                          restData={data && data.jsContent || this.state.velocity}
                        />
                      </div>
                    </TabPane>
                  </Tabs>
                  {data && data.useJsFlag != 2 ? (
                    <Item
                      className={styles.btn_wrap}
                      wrapperCol={{ span: 20, offset: 5 }}
                      label=""
                      colon={false}
                      name="varRelationship"
                    >
                      <Button type="primary" loading={tableViewLoading} onClick={this.handlePreview}>预览</Button>
                    </Item>
                  ) : null}
                  {data && data.useJsFlag != 2 ? (
                    <Item
                      labelCol={{ span: 5 }}
                      wrapperCol={{ span: 19 }}
                      label="计算结果"
                    >
                      <ProTable
                        loading={tableViewLoading}
                        rowKey={() => (Math.random())}
                        columns={tablePreviewColumn}
                        dataSource={tablePreview}
                        scroll={{ x: true, y: 110 }}
                        pagination={false}
                      />
                    </Item>
                  ) : null}
                </div>
              ) : null}
              <Form.Item>
                <div className={styles.column}>数据目标</div>
              </Form.Item>
              <Form.Item
                label={
                  <span>数据目标
                    <Tooltip
                      placement="top"
                      title={
                        <div>
                          <p>来源是MQTT、Kafka的时候，使用velocity模板解析目标只能选择IoTDB</p>
                        </div>
                      }
                    >
                      <i className="iconfont icon-yiwentishi" />
                    </Tooltip>
                  </span>
                }
              >
                <div className={`${styles.form_item} ${styles.text_overflow_single}`} title={data && data.targetDsName}>{data && data.targetDsName}</div>
              </Form.Item>
              {data && data.useJsFlag == 2 ? null : (
                <div className={styles.target_table}>
                  <Form.Item
                    label={data && data.targetDsType === 'Kafka' ? 'Topic' : '目标表'}
                  >
                    <div className={`${styles.form_item} ${styles.text_overflow_single}`} title={data && data.targetTableOrTopic}>{data && data.targetTableOrTopic}</div>
                  </Form.Item>
                </div>
              )}
              {(data && data.sourceDsType !== 'Mongodb' && data.targetDsType === 'Kafka') || (data && data.targetDsType === 'MQTT') || (data && data.useJsFlag == 2) ? null : (
                <div>
                  <Form.Item>
                    <div className={styles.column}>字段映射</div>
                  </Form.Item>
                  <div className={styles.field_mapping}>
                    <FieldMapping
                      {...{
                        source: {
                          data: sourceFields,
                          columns: sourceCols,
                          mutiple: false,
                        },
                        target: {
                          data: targetFields,
                          columns: data?.targetDsType === 'InfluxDB' ? influxDBCols : sourceCols,
                          mutiple: false,
                        },
                        relation,
                        edit: false,
                        onChange: (relations) => {
                          this.setState({
                            relation: relations,
                          })
                        },
                      }}
                    />
                  </div>
                </div>
              )}
            </Form>
          </div>
        </div>
      </div>
    )
  }
}
